<template>
    <div class="app-container">
        <div class="head">
            <img src="@/assets/img/Layout/position.png" />
            <p class="see-block">领料单新建</p>
        </div>
        <div class="view-container">
            <el-row class="status-title">
                <el-col class="mr20 width100">
                    <el-button
                        class="btn-success width100"
                        type="primary"
                        @click="submitForm()"
                    >确定</el-button>
                </el-col>
                <el-col :span="10" class="status-container">
                    <div class="status-item">
                        <span class="active">草稿</span>
                        <span>待审核</span>
                        <span>待领用</span>
                        <span>已领用</span>
                    </div>
                </el-col>
            </el-row>
            <el-form ref="form" :model="form" label-width="100px" class="mt30">
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="单据编码:" prop="code">
                            <el-input v-model="form.code" placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="业务日期:" prop="businessDate">
                            <el-date-picker value-format="yyyy-MM-dd" v-model="form.businessDate" suffix-icon="el-icon-date" type="date" placeholder="" :picker-options="pickerOptions" style="width:100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="业务部门:" prop="businessUnit">
                            <el-select v-model="form.businessUnit" style="width:100%;" placeholder="请选择">
                                <el-option label="生产部" value="生产部"></el-option>
                                <el-option label="财务部" value="财务部"></el-option>
                                <el-option label="质检部" value="质检部"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="业务类型:" prop="businessType">
                            <el-select v-model="form.businessType" style="width:100%;" placeholder="请选择" @change="onBusinessType">
                                <el-option label="生产领料" value="0"></el-option>
                                <el-option label="赠品领用" value="1"></el-option>
                                <el-option label="质检领用" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="领用仓库:" prop="receivingWarehouse">
                            <el-select v-model="form.receivingWarehouse" style="width:100%;" placeholder="请选择">
                                <el-option
                                    v-for="item in warehouseList"
                                    :key="item.warehouseId"
                                    :label="item.name"
                                    :value="item.warehouseId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <template v-if="businessType == true">
                        <el-col :span="9">
                            <el-form-item label="完工入库单:" prop="planFinishCode">
                                <el-autocomplete
                                    style="width:100%;"
                                    v-model="form.planFinishCode"
                                    :fetch-suggestions="searchPlanFinishCode"
                                    placeholder="请选择"
                                    @select="onPlanFinishCode"
                                    @clear="onPlanFinishClear"
                                    clearable
                                ></el-autocomplete>
                            </el-form-item>
                        </el-col>
                    </template>
                    <el-col :span="9">
                        <el-form-item label="领料人:" prop="picker">
                            <el-select v-model="form.picker" style="width:100%;" placeholder="请选择">
                                <el-option
                                    v-for="item in pickerList"
                                    :key="item.userId"
                                    :label="item.userName"
                                    :value="item.userName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-model="form.remark" placeholder="" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-table :data="productData">
                            <el-table-column label="序号" type="index" align="center" width="50" />
                            <el-table-column :label="item.label" :prop="item.prop" :width="item.width" v-for="(item, index) in columns" :key="index" align="center">
                                <template slot-scope="scope">
                                    <template v-if="planFinishType == '1'">
                                        <template v-if="item.type == 'num'">
                                            <el-input placeholder="请输入数量" v-model="scope.row[item.prop]" @input="(val) => inputNum(val, scope.row)" />
                                        </template>
                                        <template v-else>
                                            {{ scope.row[item.prop] }}
                                        </template>
                                    </template>
                                    <template v-else>
                                        <template v-if="item.type == '1'">
                                            <el-autocomplete
                                                style="width:74%;margin-right:5px;"
                                                v-model="scope.row[item.prop]"
                                                :fetch-suggestions="searchCode"
                                                placeholder="请输入"
                                                @select="val => handleSelect(val, scope.row, scope.$index)"
                                            ></el-autocomplete>
                                            <el-button type="primary" size="small" class="btn-success" icon="el-icon-search" @click="searchProductSku"></el-button>
                                        </template>
                                        <template v-if="item.type == '2'">
                                            <el-autocomplete
                                                style="width:74%;margin-right:5px;"
                                                v-model="scope.row[item.prop]"
                                                :fetch-suggestions="searchName"
                                                placeholder="请输入"
                                                @select="val => handleSelect(val, scope.row, scope.$index)"
                                            ></el-autocomplete>
                                            <el-button type="primary" size="small" class="btn-success" icon="el-icon-search" @click="searchProductSku"></el-button>
                                        </template>
                                        <template v-if="item.type == '3'">
                                            {{ scope.row[item.prop] }}
                                        </template>
                                        <template v-if="item.type == 'num'">
                                            <el-input placeholder="请输入数量" v-model="scope.row[item.prop]" @input="(val) => inputNum(val, scope.row)" />
                                        </template>
                                        <template v-if="item.type == 'batch'">
                                            <template v-if="scope.row.isSerial == '0'">
                                                <el-input placeholder="" v-model="scope.row[item.prop]" disabled />
                                            </template>
                                            <template v-else>
                                                <template v-if="scope.row.enableBatches == '0'">
                                                    <el-input v-model="scope.row[item.prop]" placeholder="请输入批次号" @change="onChangeBatch" />
                                                </template>
                                                <template v-else>
                                                    <el-input placeholder="未启用批次" disabled />
                                                </template>
                                            </template>
                                        </template>
                                        <template v-if="item.type == 'realNum'">
                                            <el-input placeholder="" v-model="scope.row[item.prop]" disabled />
                                        </template>
                                        <template v-if="item.type == 'warehouse'">
                                            <el-select v-model="scope.row[item.prop]" style="width:100%;" placeholder="请选择">
                                                <el-option
                                                    v-for="item in warehouseList"
                                                    :key="item.warehouseId"
                                                    :label="item.name"
                                                    :value="item.warehouseId">
                                                </el-option>
                                            </el-select>
                                        </template>
                                        <template v-if="item.type == 'position'">
                                            <el-input v-model="scope.row[item.prop]" disabled placeholder="点击按钮搜索">
                                                <el-button slot="append" icon="el-icon-search" @click="onClickWarehouseList(scope.$index, scope.row)"></el-button>
                                            </el-input>
                                        </template>
                                        <template v-if="item.type == 'remark'">
                                            <el-input placeholder="备注" v-model="scope.row[item.prop]" />
                                        </template>
                                        <span class="del" v-if="item.type == 'del'" @click="deleteRow(scope.row, scope.$index)">删除</span>
                                    </template>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </div>
</template>

<script>
import { materialRequisitionAdd } from "@/api/system/warehouse/materialRequisition"
import { queryWarehouse } from "@/api/system/warehouse/warehouse"
import { listPlanFinish } from '@/api/system/planfinish/planfinish'
import { listProduct} from "@/api/system/basicdata/basicdata"
export default {
    name: "add",
    data() {
        return {
            form: {
                businessDate: '', // 业务日期
                businessUnit: '生产部', // 业务部门
                businessType: '0', // 业务类型
                receivingWarehouse: '', // 接收仓库
                planFinishId: '', // 完工入库单id
                planFinishCode: '', // 完工入库单名字+批次
                picker: '', // 领料人
                details: [], // 产品信息
                remark: '', // 备注
            },
            // 日期控制
            pickerOptions: {
                // disabledDate(time) {
                //     return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
                // }
            },
            businessType: false,
            warehouseList: [], // 仓库列表
            planFinishList: [], // 完工入库单数据
            planFinishType: '',
            pickerList: [], // 领料人列表
            // 表头
            columns: [{
                prop: "productCode",
                label: "物料编码",
                width: 230,
                type: '1'
            },{
                prop: "productName",
                label: "物料名称",
                type: '2',
                width: 230,
            },{
                prop: "productSpace",
                label: "物料规格",
                type: '3',
                width: 180,
            },{
                prop: "planNum",
                label: "领用数量",
                width: 120,
                type: 'num'
            },{
                prop: "batchNumber",
                label: "批次号",
                width: 150,
                type: 'batch'
            },{
                prop: "realNum",
                label: "实际数量",
                width: 100,
                type: 'realNum'
            },{
                prop: "unit",
                label: "单位",
                width: 100,
                type: '3'
            },{
                prop: "warehouse",
                label: "仓库",
                width: 130,
                type: 'warehouse'
            },{
                prop: "positionName",
                label: "仓位",
                width: 200,
                type: 'position'
            },{
                prop: "remark",
                label: "备注",
                width: 200,
                type: 'remark'
            },{
                label: "",
                type: 'del',
                width: 80
            }],
            productData: [{
                productBasicId: '', // 产品Id
                productBasicCode: '', // 产品编码
                productBasicName: '', // 产品名称
                productId: '', // sku产品Id
                productCode: '', // sku产品编码
                productName: '', // sku产品名称
                productSpace: '', // 规格
                planNum: '', // 领用数量
                batchNumber: '', // 批次号
                realNum: '', // 实际数量
                unit: '', // 单位
                warehouse: '', // 仓库
                areaId: '', // 区域id
                areaName: '', // 区域名称
                positionId: '', // 仓位id
                positionName: '', // 仓位名称
                enableBatches: '', // 是否启用批次
                isSerial: '', // 是否启用扫码
                remark: '', // 备注
            }],
            // 产品数据
            searchProduct: [],
        }
    },
    created(){
        // 获取用户信息
        let userInfo = this.$store.state.user.users
        this.form.picker = userInfo.userName
        // 领料人列表
        this.pickerList.push({
            userId: userInfo.userId,
            userName: userInfo.userName
        })
        if(this.$route.query.list){
            if(this.$route.query.productData){
                this.productData = this.$route.query.productData
            }
            this.form = this.$route.query.list
            let data = this.$route.query.data
            // console.log(data)
            let obj = {
                productId: data.productSpecificationsId,
                productCode: data.specificationCode,
                productName: data.specificationName,
                productSpace: data.value1 + data.value2,
                unit: data.unit,
                enableBatches: data.enableBatches,
                isSerial: data.isSerial
            }
            if(this.productData.length == 0){
                this.productData.push(obj)
                this.$router.push({ query: {} })
            }else{
                let idx = this.productData.findIndex(item => item.productCode == data.specificationCode)
                if(idx > -1){
                    this.$modal.msgError('产品已存在，请重新选择！')
                    this.$router.push({ query: {} })
                }else{
                    this.productData.push(obj)
                    this.$router.push({ query: {} })
                }
            }
            let arr = this.productData.filter(item => item.productCode !== '')
            this.productData = arr
            this.addProduct()
        }
        // 仓位数据
        if(this.$route.query.data && this.$route.query.data !== '[object Object]'){
            this.form = this.$route.query.data
            this.productData = this.$route.query.data.details
            this.addProduct()
            if(this.$route.query.id){
                this.$router.push({ query: {id: this.id} })
            }else{
                this.$router.push({ query: {} })
            }
        }
        this.getWarehouseList()
        this.getSearchProduct()
    },
    methods: {
        // 获取仓库列表
        getWarehouseList(){
            queryWarehouse().then(res => {
                if(res.code == 200){
                    this.warehouseList = res.data
                    if(res.data.length > 0){
                        this.form.receivingWarehouse = res.data[0].warehouseId
                    }
                }
            })
        },
        // 获取产品信息
        getSearchProduct(){
            listProduct({approvalStatus: 2, productStatus: 1}).then(res => {
                this.searchProduct = res.rows
            })
        },
        // 业务类型
        onBusinessType(e){
            if(e == '2'){
                // 质检领用
                this.businessType = true
                this.productData = []
                listPlanFinish({status: 0}).then((res) => {
                    this.planFinishList = res.rows
                })
            }else{
                // 其他
                this.businessType = false
                this.planFinishList = []
                this.form.planFinishCode = ''
                this.form.planFinishId = ''
                this.productData = []
                this.addProduct()
                this.planFinishType = ''
            }
        },
        // 完工入库单搜索
        searchPlanFinishCode(val, cb) {
            let list = []
            this.planFinishList.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.productName + '-' + item.batchNumber
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createPlanFinishFilter(val)) : arr
            cb(results)
        },
        // 匹配
        createPlanFinishFilter(val) {
            return (res) => {
                return (res.value.toLowerCase().indexOf(val.toLowerCase()) === 0)
            }
        },
        // 选中完工入库单
        onPlanFinishCode(item){
            this.productData = []
            this.planFinishType = '1'
            this.form.planFinishId = item.id
            let obj = {
                productBasicId: item.productBasicId,
                productBasicCode: item.productBasicCode,
                productBasicName: item.productBasicName,
                productId: item.productId,
                productCode: item.planCode,
                productName: item.productName,
                productSpace: item.productSpace,
                batchNumber: item.batchNumber,
                remark: item.remark
            }
            this.productData.push(obj)
        },
        // 清除完工入库单
        onPlanFinishClear(){
            this.productData = []
        },
        // 编码搜索
        searchCode(val, cb) {
            let list = []
            this.searchProduct.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.specificationCode
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 名称搜索
        searchName(val, cb){
            let list = []
            this.searchProduct.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.specificationName
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 匹配
        createFilter(val) {
            return (res) => {
                return (res.value.toLowerCase().indexOf(val.toLowerCase()) === 0)
            }
        },
        // 跳转产品分类
        searchProductSku(){
            let arr = this.productData.filter(item => item.productCode !== '')
            this.$router.push({path:"/basicData/product/sortList", query:{ type: 'materialRequisition', list: this.form, productData: arr}})
        },
        // 选中
        handleSelect(item, row, index){
            row.productBasicId = item.productId, // 产品Id
            row.productBasicCode = item.productCode, // 产品编码
            row.productBasicName = item.productName, // 产品名称
            row.productId = item.productSpecificationsId // skuId
            row.productCode = item.specificationCode // sku编码
            row.productName = item.specificationName // sku名称
            row.productSpace = item.value1 + item.value2 // 规格
            row.unit = item.unit // 单位
            row.enableBatches = item.enableBatches // 是否启用批次
            row.isSerial = item.isSerial // 是否启用扫码
            row.areaId = ''
            row.areaName = ''
            row.positionId = ''
            row.positionName = ''
            // 判断编码是否重复
            let arr = this.productData.filter(item => item.productCode !== '')
            if(arr && arr.length > 0){
                let productCode = arr.map(i => i.productCode)
                let productCodeSet = new Set(productCode)
                if(productCodeSet.size == productCode.length){
                    this.productData = arr
                    this.addProduct()
                }else{
                    this.$modal.msgError('产品已存在，请重新选择！')
                    this.productData.splice(index, 1)
                    let newArr = this.productData.filter(item => item.productCode !== '')
                    this.productData = newArr
                    this.addProduct()
                }
            }
        },
        // 数量验证
        inputNum(val, row){
            // console.log(row)
            if(val == '' || val == undefined){
                this.$modal.msgError('数量不能为空!')
            }else{
                if(/^[1-9]\d*$|^0$/.test(val) == false){
                    this.$modal.msgError('数量必须是数字！')
                    row.planNum = ''
                    return false
                }else{
                    if(JSON.parse(val) <= 0){
                        this.$modal.msgError('数量必须大于0!')
                        row.planNum = ''
                    }
                }
            }
        },
        // 批次号验证
        onChangeBatch(val){
            if(val == ''){
                this.$modal.msgError('批次号不能为空!')
            }
        },
        // 跳转仓库列表页面
        onClickWarehouseList(index, row){
            if(row.productId !== '' && row.productId !== null){
                if(row.warehouse && row.warehouse !== '' && row.warehouse !== null){
                    // 当前选中仓库对应仓库列表的数据
                    let isWarehouse = this.warehouseList.find(item => item.warehouseId == row.warehouse)
                    // 判断是否启用仓位管理
                    if(isWarehouse.openPosition == '0'){
                        this.form.details = this.productData.filter(item => item.productCode !== '')
                        this.$router.push({ path:"/warehouseManagement/warehouse/list", query:{ type: 'materialRequisition', index: index, data: this.form }})
                    }else{
                        this.$modal.msgError('未启用仓位管理！')
                    }
                }else{
                    this.$modal.msgError('请选择仓库！')
                }
            }else{
                this.$modal.msgError('请选择产品！')
            }
        },
        // 添加一条产品信息
        addProduct(){
            let data = {
                key: {
                    productId: ''
                }
            }
            this.columns.forEach(item =>{
                data.key[item.prop] = ''
            })
            this.productData.push(JSON.parse(JSON.stringify(data.key)))
        },
        // 删除数据
        deleteRow(item, index){
            if(item.productId !== ''){
                this.$modal.confirm('是否确认删除当前数据？', '删除').then(() => {
                    this.productData.splice(index, 1)
                }).catch(() => {})
            }else{
                this.$modal.msgError('最少保留一条可编辑数据！')
            }
        },
        submitForm(){
            // 判断是否是质检领用
            if(this.businessType == true){
                if(this.productData.length > 0){
                    this.getConfirm()
                }else{
                    this.$modal.msgError('请选择完工入库单！')
                }
            }else{
                // if(this.productData.length > 0){
                    this.getConfirm()
                // }else{
                //     this.$modal.msgError('请选择产品！')
                // }
            }
        },
        getConfirm(){
            // 过滤掉空数据
            let arr = this.productData.filter(item => item.productCode !== '')
            let planNum = arr.every(val => !!val.planNum)
            let enableBatches = this.productData.every(val => {
                if(val.isSerial == '1'){
                    if(val.enableBatches == '0'){
                        return !!val.batchNumber
                    }else{
                        return true
                    }
                }else{
                    return true
                }
            })
            if(arr.length > 0){
                if(planNum == true){
                    if(enableBatches == true){
                        this.form.details = arr
                        this.$modal.loading("正在提交")
                        materialRequisitionAdd(this.form).then(res => {
                            if(res.code == 200){
                                this.$modal.msgSuccess("新建成功")
                                this.$tab.closeOpenPage({ path: "/material/materialRequisition/list" })
                                this.$modal.closeLoading()
                            }
                        })
                    }else{
                        this.$modal.msgError('批次不能为空！')
                    }
                }else{
                    this.$modal.msgError('领用数量不能为空！')
                }
            }else{
                this.$modal.msgError('产品不能为空！')
            }
        },
    }
}
</script>

<style scoped>
.del{
  color: #ff0000;
  cursor: pointer;
}
</style>